import { Injectable, Inject } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { SuccessModel, ErrorModel } from '../model/ResModel'

@Injectable()
export class UsersService {
  constructor(
    @Inject('USER_REPOSITORY')
    private readonly userRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto) {
    // 入库
    const res = await this.userRepository.insert(createUserDto)
    if (res.raw.insertId) {
      return new SuccessModel('注册成功')
    } else {
      return new SuccessModel('注册失败')
    }
  }

  async findAll() {
    // 获取所有用户列表
    const res = await this.userRepository.find()
    if (res.length > 0) {
      return new SuccessModel(res);
    } else {
      return new ErrorModel()
    }
  }

  async findOne(id: number) {
    const res = await this.userRepository.findBy({ id })
    if (res.length > 0) {
      return new SuccessModel(res[0]);
    } else {
      return new ErrorModel()
    }
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    const res = await this.userRepository.update(id, updateUserDto)
    if (res.affected) {
      return new SuccessModel(res)
    } else {
      return new ErrorModel('id 不存在，更新失败')
    }
  }

  async remove(id: number) {
    const res = await this.userRepository.delete(id)
    if (res.affected) {
      return new SuccessModel('注销成功')
    } else {
      return new ErrorModel('注销失败')
    }
  }
}
